package com.unittec.drainage.sdk.root.internal.base;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.unittec.drainage.sdk.root.internal.utils.SdkUtils;
import com.unittec.drainage.sdk.root.domain.Result;

public class ResponseContent {
    private final Integer method;
    private final String resultJson;

    ResponseContent(Integer method) {
        this.method = method;
        this.resultJson = "";
    }

    ResponseContent(Integer method, String resultJson) {
        this.method = method;
        this.resultJson = resultJson;
    }

    public String getResultJson() {
        return resultJson;
    }

    public void printResult() {
        System.out.println("请求【" + this.method + "】结果如下：\r\n" + SdkUtils.toJSONString(this.resultJson,
            SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
    }

    public void formatResult() {
        SdkUtils.toJSONString(this.resultJson);
        try {
            Result<String> result = JSON.parseObject(this.resultJson, Result.class, new GatewayCodeEnumParserConfig());
            System.out.println(result);
            System.out.println(JSON.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public <T> Result<List<T>> toList(Class<T> tClass) {
        JSONObject parse = JSON.parseObject(this.resultJson);
        Result result = parse.toJavaObject(Result.class);
        if (parse.getJSONArray("data") != null) {
            result.setData(parse.getJSONArray("data").toJavaList(tClass));
        }

        return result;
    }

    @SuppressWarnings("unchecked")
    public <T> Result<T> toModel(Class<T> tClass) {
        JSONObject parse = JSON.parseObject(this.resultJson);
        return (Result<T>)parse.toJavaObject(tClass);
    }

}
